import Taro from "@tarojs/taro";
import { shareAward } from "_api/clock-in";

const TOUCH_TIME = 300;
export default {
  data() {
    return {
      imgW: "",
      imgH: "",
      startTime: "",
      endTime: "",
      canActiveLongPress: true
    };
  },
  methods: {
    touchcancel() {
      if (!this.endTime) this.endTime = +new Date();
      console.log(
        this.endTime - this.startTime,
        "touchcanceltouchcanceltouchcancel"
      );
      if (this.endTime - this.startTime >= TOUCH_TIME) {
        this.longPress();
      }
      this.gtouchReset();
    },
    async longPress() {
      console.log("长按事件触发");
      const data = await shareAward({
        reward_type: "finish_day_sign_share",
        theme_id: this.themeId,
        student_id: this.studentId
      });
      this.$emit("clockShare", {
        longPress: true,
        uuid: this.uuid,
        studentId: this.studentId,
        themeId: this.themeId,
        ...data
      });
      this.gtouchReset();
    },
    gtouchend() {
      this.endTime = +new Date();
      console.log(this.endTime - this.startTime, "gtouchend");
      if (this.endTime - this.startTime >= TOUCH_TIME) {
        this.longPress();
      }
      this.gtouchReset();
    },
    gtouchmove() {
      this.canActiveLongPress = false;
    },
    gtouchstart() {
      this.startTime = +new Date();
    },
    /* 长按事件参数重置 */
    gtouchReset() {
      this.startTime = "";
      this.endTime = "";
      this.canActiveLongPress = true;
    },
    /* 关闭弹窗 */
    close() {
      console.log("dsjdhads");
      this.$emit("update:show", false);
      this.$emit("onClose", false);
      this.hasSign = false;
    },
    saveImage() {
      const { tempFilePath } = this;
      const that = this;
      Taro.getSetting({
        success() {
          Taro.authorize({
            scope: "scope.writePhotosAlbum", // 保存图片固定写法
            success() {
              // 图片保存到本地
              Taro.saveImageToPhotosAlbum({
                filePath: tempFilePath, // 放入canvas生成的临时链接
                success(res) {
                  console.log(res);
                  Taro.hideLoading();
                  Taro.showToast({
                    title: "保存成功",
                    icon: "success",
                    duration: 4000
                  });
                }
              });
            },
            fail() {
              Taro.hideLoading();
              Taro.showToast({
                title: "您点击了拒绝微信保存图片，再次保存图片需要您进行截屏",
                icon: "none",
                duration: 3000
              });
            }
          });
        },
        fail() {
          Taro.hideLoading();
          Taro.showToast({
            title: "请先输入数据",
            icon: "none",
            duration: 3000
          });
        }
      });
    },
    /* 图片圆角处理 */
    circleImg(ctx, img, x, y, r) {
      ctx.save();
      const d = 2 * r;
      const cx = x + r;
      const cy = y + r;
      ctx.arc(cx, cy, r, 0, 2 * Math.PI);
      ctx.clip();
      ctx.drawImage(img, x, y, d, d);
      ctx.restore();
    },
    /* 文本换行处理 */
    lineFeed(cvsCtx, t, x, y, w, l, lineFeedX, lineFeedSecondWidth, centerX) {
      //参数说明
      //ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度 l:行高 lineFeedX:第二行的x起点 lineFeedSecondWidth: 第二行的文本宽度
      let chr = t.split("");
      let temp = "";
      let row = [];

      for (let a = 0; a < chr.length; a++) {
        if (!row.length) {
          if (
            cvsCtx.measureText(temp).width < w &&
            cvsCtx.measureText(temp + chr[a]).width <= w
          ) {
            temp += chr[a];
          } else {
            row.push(temp);
            temp = chr[a];
          }
        } else {
          if (
            cvsCtx.measureText(temp).width < (lineFeedSecondWidth || w) &&
            cvsCtx.measureText(temp + chr[a]).width <=
              (lineFeedSecondWidth || w)
          ) {
            temp += chr[a];
          } else {
            row.push(temp);
            temp = chr[a];
          }
        }
      }
      row.push(temp);
      for (let b = 0; b < row.length; b++) {
        cvsCtx.fillText(
          row[b],
          centerX
            ? (644 - cvsCtx.measureText(row[b]).width) / 2
            : b > 0
            ? lineFeedX || x
            : x,
          y + (b >= 1 ? b * l : 0)
        ); //每行字体y坐标间隔20
      }
    },
    /* 开始画图 */
    async drawCanvas(data, fun) {
      const cvsCtx = Taro.createCanvasContext(this.canvasId, this.$scope);
      for (const i in data) {
        data[i].type === "image" &&
          (await this.canvasImageCreate(cvsCtx, data[i]));
        /* 在底图加载之后加载 额外的 以免被底图覆盖 */
        if (~~i === 1) {
          fun && fun(cvsCtx);
        }
        data[i].type === "text" &&
          (await this.canvasTextCreate(cvsCtx, data[i]));

        /**画渐变背景 */
        if (data[i].type === "GRADUAL_BG") {
          await this.handleDrawGradualBg(cvsCtx, data[i]);
        }
      }
      cvsCtx.draw(false, res => {
        console.log(res, "resresres");
        this.canvasToImage();
      });
    },
    /* canvas图片处理 */
    async canvasImageCreate(cvsCtx, option) {
      const info = await Taro.getImageInfo({ src: option.value });
      console.log(info);
      if (option.bg) {
        this.imgW = info.width;
        this.imgH = info.height;
      }
      let width = option.width || info.width;
      let height = option.height || info.height;
      let positionX = option.position ? option.position[0] : 0;
      let positionY = option.position ? option.position[1] : 0;
      const dWidth = option.dWidth || width;
      const dHeight = option.dHeight || height;
      option.radius
        ? this.circleImg(
            cvsCtx,
            info.path,
            positionX,
            positionY,
            Math.ceil(dWidth / 2)
          )
        : cvsCtx.drawImage(
            info.path,
            0,
            0,
            width,
            height,
            positionX,
            positionY,
            dWidth,
            dHeight
          );
    },
    /* canvas文字处理 */
    canvasTextCreate(cvsCtx, option) {
      let size = option.fontSize || 16; /* 默认字体大小 */
      cvsCtx.setFontSize(size);
      option.color && cvsCtx.setFillStyle(option.color);
      /* 文字默认左下角 展示在画布 0 , 0 处 */
      /* y轴需要加上文字大小 把文字左上角定位在画布 0,0 处再定位 */
      const xPosition = option.centerX
        ? option.centerWidth
          ? (option.centerWidth - cvsCtx.measureText(option.value).width) / 2 +
            option.position[0] - ((cvsCtx.measureText(option.value).width <= 5) ? 7 : 0)/* 做偏移量兼容手机显示 */
          : (644 - cvsCtx.measureText(option.value).width) / 2
        : option.position[0];
      console.log(xPosition);
      option.lineFeed
        ? this.lineFeed(
            cvsCtx,
            option.value,
            xPosition,
            size + option.position[1],
            option.lineFeedWidth,
            option.lineHeight,
            option.lineFeedX,
            option.lineFeedSecondWidth,
            option.centerX
          )
        : cvsCtx.fillText(option.value, xPosition, size + option.position[1]);
    },
    /**canvas绘制渐变背景 */
    handleDrawGradualBg(
      cvsCtx,
      { startPoint, gradualColor, position, width, height }
    ) {
      const [x, y, x1, y1] = startPoint;
      const [startColor, endColor] = gradualColor;
      const [positionX, positionY] = position;
      const grd = cvsCtx.createLinearGradient(x, y, x1, y1); // 渐变色的起点坐标
      grd.addColorStop(0, endColor);
      grd.addColorStop(1, startColor);
      cvsCtx.setFillStyle(grd);
      cvsCtx.fillRect(positionX, positionY, width, height);
    },

    /* 绘制圆角矩形 */
    drawRoundRect(cxt, x, y, width, height, radius) {
      cxt.beginPath();
      cxt.arc(x + radius, y + radius, radius, Math.PI, (Math.PI * 3) / 2);
      cxt.lineTo(width - radius + x, y);
      cxt.arc(
        width - radius + x,
        radius + y,
        radius,
        (Math.PI * 3) / 2,
        Math.PI * 2
      );
      cxt.lineTo(width + x, height + y - radius);
      cxt.arc(
        width - radius + x,
        height - radius + y,
        radius,
        0,
        (Math.PI * 1) / 2
      );
      cxt.lineTo(radius + x, height + y);
      cxt.arc(
        radius + x,
        height - radius + y,
        radius,
        (Math.PI * 1) / 2,
        Math.PI
      );
      cxt.closePath();
    }
  }
};
